# 利用DDA算法及颜色插值绘制彩色直线，L1(Point(10, 10，红色), Point(100, 80，蓝色))。
import numpy as np
import matplotlib.pyplot as plt
width = 460
height = 460
def color_interpolation(x, x1, c1, x2, c2):
    if x2 == x1:
        return c1
    t = (x - x1) / (x2 - x1)
    r = int(c1[0] * (1 - t) + c2[0] * t)
    g = int(c1[1] * (1 - t) + c2[1] * t)
    b = int(c1[2] * (1 - t) + c2[2] * t)
    return (r, g, b)

def axis_shift(x, y):
    # 到坐标原点
    return (x, height - 1 - y)

def draw_dda_line(x1, y1, c1, x2, y2, c2, img):
    # 计算两点之间的距离
    dx = x2 - x1
    dy = y2 - y1
    # 确定步骤数，取决于在哪个方向上跨度更大
    steps = max(abs(dx), abs(dy))
    if steps == 0:
        steps = 1
    # 计算每一步的增量
    x_inc = dx / steps
    y_inc = dy / steps
    # 起始点
    x, y = x1, y1
    # 在图像上绘制点
    for _ in range(steps + 1):
        # 计算颜色 print(color)
        color = color_interpolation(int(x), x1, c1, x2, c2)
        # 设置当前栅格点颜色
        if 0 <= int(x) < width and 0 <= int(y) < height:
            img[int(y), int(x)] = color
        # 沿主位移步进
        x += x_inc
        y += y_inc

# 加载或创建一个图像
img = np.zeros((height, width, 3), dtype=np.uint8)  # 创建一个256x256的黑色画布

# 绘制线段
draw_dda_line(*axis_shift(10, 10), (255, 0, 0), *axis_shift(200, 100), (0, 0, 255), img)

# 显示图像
plt.imshow(img)
plt.show()
